package com.study.talk.app.moment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.study.talk.R;
import com.study.talk.adapter.MomentListAdapter;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.databinding.ActivityMomentListBinding;
import com.study.talk.entity.resp.MomentResponse;
import com.study.talk.listener.SoftKeyBoardListener;
import com.study.talk.net.NetApi;
import com.study.talk.util.ToastUtil;
import com.study.talk.util.alert.AlertUtil;

import java.util.List;

public class MomentListActivity extends BaseActivity {

    public static final int MOMENT_ALL = 0;
    public static final int MOMENT_FRIEND = 1;
    public static final int MOMENT_SELF = 2;

    private ActivityResultLauncher<PickVisualMediaRequest> imageChooseLauncher;

    private List<MomentResponse> momentResponseList;

    public ActivityMomentListBinding activityMomentListBinding;

    public static final String typeName = "MOMENT_LIST_TYPE";
    public static final String dataName = "USER_ID";

    private int momentListType = 0;
    private int userId = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMomentListBinding = ActivityMomentListBinding.inflate(getLayoutInflater());
        setContentView(activityMomentListBinding.getRoot());

        setSupportActionBar(activityMomentListBinding.momentListToolbar);
        initKeyBoard();
        initLauncher();
        initData();
        initView();
    }


    //如果是在只看朋友的朋友圈，就不显示添加朋友圈的menu
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        switch (momentListType) {
            case MOMENT_FRIEND -> menu.findItem(R.id.moment_menu_item).setVisible(false);
            case MOMENT_ALL, MOMENT_SELF -> menu.findItem(R.id.moment_menu_item).setVisible(true);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.moment_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    private void initKeyBoard() {
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {

            @Override
            public void keyBoardShow(int height) {
                //键盘当前被唤出，显示评论输入框控件，但是其实只有评论输入框控件显示事才会有键盘被唤出的可能
                activityMomentListBinding.momentListCommentLinearLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void keyBoardHide(int height) {
                //隐藏键盘监听回调，影藏输入框控件
                activityMomentListBinding.momentListCommentLinearLayout.setVisibility(View.GONE);
            }
        });
    }

    private void initLauncher() {
        imageChooseLauncher = registerForActivityResult(new ActivityResultContracts.PickMultipleVisualMedia(9), results -> {
            if (results == null || results.isEmpty()) {
                AlertUtil.show(MomentListActivity.this, "操作提醒", "你没有选择任何照片，是打算发一个没有图片的动态吗?", b -> {
                    if (b)
                        startActivity(new Intent(MomentListActivity.this, AddMomentActivity.class));
                });
            } else {
                getApp().dataMap.put("imageList", results);
                handler.postDelayed(() -> startActivity(new Intent(MomentListActivity.this, AddMomentActivity.class)), 500);
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        momentListType = intent.getIntExtra("MOMENT_LIST_TYPE", 0);
        userId = intent.getIntExtra("USER_ID", getApp().userId());
    }

    private void initView() {

        activityMomentListBinding.momentRecycleView.setLayoutManager(new LinearLayoutManager(this));

        //加载头像
        loadUserAvatar(activityMomentListBinding.momentListUserAvatar);

        //点击返回按钮
        activityMomentListBinding.momentListToolbar.setNavigationOnClickListener(v -> finish());

        //选择图片新增朋友圈
        activityMomentListBinding.momentListToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.moment_menu_item){
                    imageChooseLauncher.launch(new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build());
                }
                return true;
            }
        });


    }

    public void getData() {
        if (momentListType == MOMENT_ALL) {
            NetApi.getFriendMomentList(getApp().user.getId(), data -> {
                momentResponseList = data;
                MomentListAdapter adapter = new MomentListAdapter(momentResponseList, this, activityMomentListBinding);
                runOnUiThread(() -> activityMomentListBinding.momentRecycleView.setAdapter(adapter));
            }, msg -> runOnUiThread(() -> ToastUtil.showToast(MomentListActivity.this, msg)));
        } else {
            NetApi.getUserMomentList(userId, data -> {
                momentResponseList = data;
                MomentListAdapter adapter = new MomentListAdapter(momentResponseList, this, activityMomentListBinding);
                runOnUiThread(() -> activityMomentListBinding.momentRecycleView.setAdapter(adapter));
            }, msg -> runOnUiThread(() -> ToastUtil.showToast(MomentListActivity.this, msg)));
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        getData();
    }
}